<?php

class JFX_Image
{


    public static function resize($fileName, $w, $h, $jpgQuality=80, $prop=true, $pad=true, $bgColor='')
    {
        if($bgColor == '') $bgColor = array(255, 255, 255);
        $dims=getimagesize($fileName);
        if($prop){
            // calculate proportions
            if(($dims['0']/$w)>($dims['1']/$h)){
      	        // width rules
      	        $newW = $w;
      	        $newH=self::proportionateTo($dims['0'],$w,$dims['1']);
      	    }else{
      	        //height rules
      	        $newH = $h;
      	        $newW=self::proportionateTo($dims['1'],$h,$dims['0']);
      	    };
      	    if($pad){
                if($newW < $w){
                    // have to pad vertically
                    $innerW = $newW;
                    $newW = $w;
                    $lPos = (($w-$innerW)/2);
                }else{
                    $lPos = 0;
                    $innerW = $w;
                }
                if($newH < $h){
                    // have to pad vertically
                    $innerH = $newH;
                    $newH = $h;
                    $tPos = (($h-$innerH)/2);
                }else{
                    $tPos = 0;
                    $innerH = $h;
                }
                //echo 'innerH: '.$innerH.', innerW: '.$innerW.', newH: '.$newH.', newW: '.$newW.', tpos: '.$tPos.', lPos: '.$lPos.'<br />';
            };
            if($newW > $dims[0] && $newH > $dims[1]){
                // we do not blow-up small images, only pad them
                $innerW = $dims[0];
                $innerH = $dims[1];
                $lPos = round(($newW-$dims[0])/2);
                $tPos = round(($newH-$dims[1])/2);
            };

        }else{
            $newW = $w;
            $newH = $h;
        };

        $ext = self::getImageExt($fileName);
        //echo $fileName.'<br />';
		@ini_set('memory_limit', '50m');
        switch($ext){
            case'.jpg':
      	      global $jpg_quality;
      	      $image = imagecreatefromjpeg($fileName);
      	      $image_p = imagecreatetruecolor($newW, $newH);
      	      $color = imagecolorallocate($image_p, $bgColor[0], $bgColor[1], $bgColor[2]);
      	      imagefill($image_p, 0, 0, $color);
      	      if(!$pad) imagecopyresampled($image_p, $image, 0, 0, 0, 0, $newW, $newH, $dims['0'], $dims['1']);
      	      else imagecopyresampled($image_p, $image, $lPos, $tPos, 0, 0, $innerW, $innerH, $dims['0'], $dims['1']);
//echo 'image: '.$image_p.', '.$fileName.' , '.$jpgQuality.' , '.$w. ' , '.$h.'<br />';

              $image = imagejpeg($image_p, $fileName, $jpgQuality);
			  
            break;
            case'.gif':
      	      $image = imagecreatefromgif($fileName);
      	      $image_p = imagecreatetruecolor($newW, $newH);
      	      $color = imagecolorallocate($image_p, $bgColor[0], $bgColor[1], $bgColor[2]);
      	      imagefill($image_p, 0, 0, $color);
              if(!$pad) imagecopyresampled($image_p, $image, 0, 0, 0, 0, $newW, $newH, $dims['0'], $dims['1']);
      	      else imagecopyresampled($image_p, $image, $lPos, $tPos, 0, 0, $innerW, $innerH, $dims['0'], $dims['1']);
              $image = imagegif($image_p,$fileName);
      	    break;
            case'.png':
          	  $image = imagecreatefrompng($fileName);
      	      $image_p = imagecreatetruecolor($newW, $newH);
      	      $color = imagecolorallocate($image_p, $bgColor[0], $bgColor[1], $bgColor[2]);
      	      imagefill($image_p, 0, 0, $color);
      	      if(!$pad) imagecopyresampled($image_p, $image, 0, 0, 0, 0, $newW, $newH, $dims['0'], $dims['1']);
              else imagecopyresampled($image_p, $image, $lPos, $tPos, 0, 0, $innerW, $innerH, $dims['0'], $dims['1']);
              $image = imagepng($image_p,$fileName);
      	    break;
        };
    }



    public static function getImageExt($pathName)
    {  //echo __LINE__.'<br />';

        if(!file_exists($pathName)){
            JFX::addError('File does not exist.');
            return false;
        };  //echo __LINE__.'<br />';
        $dims=getimagesize($pathName);

        //echo 'MIME:'.$dims['2'].'-'.$pathName.BR;exit;
        switch($dims['2']){
           case'3':return '.png';
           case'2':return '.jpg';
           case'1':return '.gif';
           case'4':return '.swf';
           case'5':return '.psd';
           case'6':return '.bmp';
           case'7':return '.tif';
           case'8':return '.tif';
           default:JFX::addError('Unidentified image type.<br />');  //echo __LINE__.'<br />';
           return false;
        };
    }




    public static function uploadFromForm($name, $dest, $w, $h, $jpgQuality, $prop=true, $intelliExt=true, $del=true)
    {
        if(!isset($_FILES[$name]['tmp_name'])||$_FILES[$name]['tmp_name']==''){
            JFX::addError('Could not upload the file. Temp file not found.<br />');  //echo __LINE__.'<br />';
      	    return false;
        };
        if($intelliExt){
      	    if(!$ext=self::getImageExt($_FILES[$name]['tmp_name'])){  //echo __LINE__.'<br />';
              return false;
            };
            preg_replace('/.*\..{3}$/',$ext,$dest);
        }else{
            $ext=substr($dest,strlen($dest)-4);
        };
        // now it is time to move and upload the img
        if($del){
            rename($_FILES[$name]['tmp_name'],$dest);
        }else{
            copy($_FILES[$name]['tmp_name'],$dest);
        };
        $dims=getimagesize($dest);  //echo __LINE__.'<br />';
        if($prop){
            // calculate proportions
            if(($dims['0']/$w)>($dims['1']/$h)){
      	        // width rules
      	        $h=self::proportionateTo($dims['0'],$w,$dims['1']);
      	    }else{
      	        //height rules
      	        $w=self::proportionateTo($dims['1'],$h,$dims['0']);
      	    };
        };
           //echo __LINE__.$ext.'<br />';


        switch($ext){
            case'.jpg':
      	      global $jpg_quality;
      	      $image = imagecreatefromjpeg($dest);
      	      $image_p = imagecreatetruecolor($w, $h);
      	      imagecopyresampled($image_p, $image, 0, 0, 0, 0, $w, $h, $dims['0'], $dims['1']);
      	      $image = imagejpeg($image_p,$dest,$jpgQuality);
      	  break;
          case'.gif':
      	      $image = imagecreatefromgif($dest);
      	      $image_p = imagecreatetruecolor($w, $h);
      	      imagecopyresampled($image_p, $image, 0, 0, 0, 0, $w, $h, $dims['0'], $dims['1']);
              $image = imagegif($image_p,$dest);
      	  break;
          case'.png':
          //echo __LINE__.'<br />';
          	  $image = imagecreatefrompng($dest);
      	      $image_p = imagecreatetruecolor($w, $h);
      	      imagecopyresampled($image_p, $image, 0, 0, 0, 0, $w, $h, $dims['0'], $dims['1']);
              $image = imagepng($image_p,$dest);
              //echo $dest.'<br />';
      	  break;
          default:
              JFX::addError('Invalid image type.');
              return false;
        };
        return true;
    }


    /**
     * Used for calculating the new height if the width has been changed, or vice-versa
     * Eg:
     * // we will already know both dimensions of our origninal image:
     * $width1 = 800;
     * $height1 = 600;
     * // we will know the desired dimension of one side:
     * $width2 = 400;
     * // now this function is handy to calculate the resulting width of our variable side:
     * $height2 = Antz_Image::proportionateTo($width1, $width2, $height1);
     */
    public static function proportionateTo($orig, $new, $subject){
        return(($new*$subject)/$orig);
    }// end function










}
